// import Vue from "vue";
import axios from "axios";
import {
	API_ROOT
} from '@/config/env.js'
// import store from "@/store";
// import router from "@/router";

// 添加请求拦截器
// axios.interceptors.request.use(function (config) {
//   let req = config.data;
//   // debugger
//   let operateNeedLogin_actions = ['hospital_fork'];//需要登录的操作
//   if((typeof req.user_id != 'undefined' && !req.user_id)

//   // && (typeof req.token != 'undefined' && !req.token)

//   ){
//     console.log('此操作需要授权， 当前用户未没有登录')

//     alert('请先登录');
//     store.commit('clear_loginInfo')

//     router.push({
//       path: "/login",
//       query: {
//         mode: "noLogin",
//       },
//     });

//     return Promise.reject(config);
//   }

//   return config;
// }, function (error) {
//   // 对请求错误做些什么
//   return Promise.reject(error);
// });

// 添加请求拦截器
axios.interceptors.request.use(
	function (config) {
		let req = config.data;
		// if (!req) {
		//   return false;
		// }

		// let currApiName = req.action; //当前接口名称
		// let currRoute = router.history.current; //当前路由
		// let token = localStorage.getItem("token");

		// if (req._no_tip) {
		//   // debugger
		//   // delete req._no_tip
		// }
		// // console.log('接口数据拦截', req)

		// // let currRouteNeedAuth = currRoute.meta ? currRoute.meta.requireAuth : false; //当前路由是否需要授权
		// // console.log("当前路由是否需要授权 currRouteNeedAuth = ", currRouteNeedAuth);
		// // console.log("当前接口名称 currRouteNeedAuth = ", currRouteNeedAuth);

		// // 跳转登录： 当前接口需要登录
		// if (!token && needAuthApi.includes(currApiName)) {
		//   alertErr("请您先登录");
		//   store.commit("clear_loginInfo");

		//   // let is_wx_auth = true; //是否微信授权登录项目
		//   if (!store.state.is_weChat_auth) {
		//     let fullPath_encode = encodeURIComponent(currRoute.fullPath);
		//     router.push({
		//       path: "/login",
		//       query: {
		//         fullPath: fullPath_encode,
		//       },
		//     });
		//   } else {
		//     store.commit("set_weixinReAuth", new Date().getTime());
		//   }

		//   // debugger;
		//   // return config;
		//   return Promise.reject(config);
		// }

		return config;
	},
	function (error) {
		// 对请求错误做些什么
		return Promise.reject(error);
	}
);

// 添加响应拦截器
axios.interceptors.response.use(
	function (res) {
		let data = res.data;

		// debugger
		// if (data && (data.code == 2 || data.code == -1 || data.code == -2)) {
		//   //微信授权项目 重新微信授权
		//   //非微信授权登录项目  跳转登录页
		//   if (store.state.is_weChat_auth) {
		//     data.message = "登录过期或未登录，请您先登录";
		//     store.commit("clear_loginInfo"); //清除登录数据
		//   } else {
		//     data.message = "登录过期或未登录，请您先登录";
		//     store.commit("clear_loginInfo"); //清除登录数据

		//     router.push({
		//       path: "/login",
		//       query: {
		//         mode: "noLogin",
		//       },
		//     });
		//   }
		// } else if (data && data.code == 0) {
		//   //操作失败提示
		//   let is_upload = res.config.data instanceof FormData;
		//   let actionStr = "";
		//   let actionName = "";
		//   if (is_upload) {
		//     actionStr = "";
		//     actionName = "index_upload";
		//   } else {
		//     actionStr = res.config.data.split("&").find((v) => v.includes("action"));
		//     actionName = actionStr.split("=")[1];
		//   }

		//   if (actionName) {
		//     if (ApiList_failActionTip.includes(actionName)) {
		//       alertErr(res.data.message);
		//     }
		//   }
		// } else if (data && data.code == 200) {
		//   //操作成功提示
		//   let is_upload = res.config.data instanceof FormData;
		//   let actionStr = "";
		//   let actionName = "";
		//   let _no_tip_str = "";
		//   let _no_tip = "";

		//   if (is_upload) {
		//     actionStr = "";
		//     actionName = "index_upload";
		//   } else {
		//     let arr_params = res.config.data.split("&");
		//     actionStr = arr_params.find((v) => v.includes("action"));
		//     actionName = actionStr.split("=")[1];

		//     _no_tip_str = arr_params.find((v) => v.includes("_no_tip"));
		//     if (_no_tip_str) {
		//       _no_tip = _no_tip_str.split("=")[1];
		//     }
		//     console.log("操作成功提示 _no_tip", _no_tip);
		//   }

		//   // if (actionName) {
		//   //   // if (ApiList_successActionTip.includes(actionName) && _no_tip != 1) {
		//   //   //   alertSucc(res.data.message || "操作成功");
		//   //   // }
		//   // }
		// }

		return data;
	},
	function (error) {
		console.log("-------------- axios拦截 error----------------");
	}
);

// 普通接口
// this.$api({
//   url: "setting",
//   method: "get",
//   data: {
//     params1: "val",
//   },
// }).then((res) => {
//   if (res.code == 200) {
//   }
// });

// this.$api({
//     params1: "val",
//     params2: "val",
// }).then((res) => {
//   if (res.code == 200) {
//   }
// });

function api(option) {
	// console.log('api 接口请求 option', option)

	//option 需要定义如下参数
	//请求地址 url
	//请求方式 method (get || post)
	//请求数据 data
	let token = localStorage.getItem("token");
	// let {
	//   //
	//   url,
	//   method,
	//   data,
	// } = option;

	let reqUrl = process.env.NODE_ENV !== "production" ? API_ROOT : "/admin_service.php"
	let method = option.method || "get"; //

	// if (option.action) {
	//   reqUrl += "?action=" + option.action;
	//   // reqUrl += "?";
	// }

	// let reqData = new FormData();
	// for (var key in option) {
	//   reqData.append(key, option[key]);
	// }

	let reqData = {
		...option.data,
		// user_id: localStorage.getItem("user_id"),
		token: localStorage.getItem("token"),
	};



	// 测试使用
	// token = `eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6IjRmYmYwYjM2LTg4MWMtNDBiZC1iNjBkLWNhMjFjZGM1YjRhOSIsInVzZXJuYW1lIjoiYWRtaW4ifQ.RVRkc0pL5GSqlGIz3rFnfhO8NzUyIvqw1SlbTR8leMByI2tyXr8pulNjJnwAomIwiB0P4B2y0xz9FvQoSQ3B8g`;
	let otherConfig = {
		headers: {
			"Content-Type": "application/x-www-form-urlencoded",
			// "Content-Type": "application/json",
			// Authorization: "Bearer " + token,
		},
		transformRequest: [
			function (data) {
				let ret = "";
				let i = 0;
				for (let key in data) {
					if (i != 0) {
						ret += "&";
					} else { }
					if (key != "action") {
						// debugger
						ret +=
							encodeURIComponent(key) + "=" + encodeURIComponent(data[key]);
						i++;
					}
				}
				return ret;
			},
		],
	};

	//特殊处理上传
	if (reqUrl.includes("/file/api/v1/app/upload")) {
		otherConfig.headers["Content-Type"] = "application/form-data";
	}

	if (method == "get") {
		return axios({
			url: reqUrl,
			method: method,
			params: reqData,
			...otherConfig,
		});
	} else if (method == "post" || method == "put" || method == "delete") {
		return axios({
			url: reqUrl,
			method: method,
			data: reqData,
			...otherConfig,
		});
	}
}

function apiUploadImage(option) {
	let {
		file
	} = option;

	const formData = new FormData();
	formData.append("action", 'upload_uploadImg');
	formData.append("token", localStorage.getItem("token"));
	formData.append("file", file);

	let url = process.env.NODE_ENV !== "production" ? API_ROOT : "/admin_service.php"
	return axios({
		url: url,
		method: "post",
		headers: {
			"Content-Type": "multipart/form-data;boundary=" + new Date().getTime(),
		},
		transformRequest: [],
		data: formData,
	});
}


function apiUploadVideo(option) {
	let {
		file
	} = option;

	const formData = new FormData();
	formData.append("action", 'upload_uploadFile');
	formData.append("token", localStorage.getItem("token"));
	formData.append("file", file);

	let url = process.env.NODE_ENV !== "production" ? API_ROOT : "/admin_service.php"
	return axios({
		url: url,
		method: "post",
		headers: {
			"Content-Type": "multipart/form-data;boundary=" + new Date().getTime(),
		},
		transformRequest: [],
		data: formData,
	});
}


function apiUploadFile(option) {
	let {
		file
	} = option;

	const formData = new FormData();
	formData.append("action", 'upload_uploadFile');
	formData.append("token", localStorage.getItem("token"));
	formData.append("file", file);

	let url = process.env.NODE_ENV !== "production" ? API_ROOT : "/admin_service.php"
	return axios({
		url: url,
		method: "post",
		headers: {
			"Content-Type": "multipart/form-data;boundary=" + new Date().getTime(),
		},
		transformRequest: [],
		data: formData,
	});
}

// 文件上传
function uploadApi(formData, params = {}) {
	let token = localStorage.getItem('token') || '';
	if (token) {
		// params.token = token;
		formData.append('token', token);
		formData.append("action", 'setting_updateH5');
	}
	let url = process.env.NODE_ENV !== "production" ? API_ROOT : "/admin_service.php"
	return axios({
		url,
		method: 'post',
		headers: {
			"Content-Type": "multipart/form-data;boundary=" + new Date().getTime(),
		},
		transformRequest: [],
		data: formData,
		// params
	});
}

export default {
	api,
	apiUploadImage,
	apiUploadVideo,
	apiUploadFile,
	uploadApi
};